//
//  LZVideoCellPresenterForCoupon.m
//  laziz_Consumer
//
//  Created by xbnzd on 17/4/19.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZVideoCellPresenterForCoupon.h"

#import "LZGrabCouponAndFightGroupsDetialModel.h"
#import "LZPromotionStatusModel.h"
#import "LZVideoListModel.h"

#import "LZCheckCouponAndGrouponPresenter.h"
#import "LZCouponPresenter.h"

#import "LZGrabCouponDetailViewController.h"
#import "LAMerchantDetailTableView.h"
#import "LZHomePageViewController.h"
#import "LZGrabCouponDetailPopView.h"
#import "LZLoginViewController.h"
#import "LZAlertView.h"

#import "LZUserModel.h"
#import "extobjc.h"

#import "LZVideoTableViewCell.h"

@interface LZVideoCellPresenterForCoupon ()

@property (nonatomic, copy) NSString *selectedIndexPathIdentifier;

@property (nonatomic, strong) LZGrabCouponDetailPopView *couponDetailPopView;

@property (nonatomic, strong)  LZPromotionStatusModel *statusModelTemp;

@end

@implementation LZVideoCellPresenterForCoupon

- (void)couponDealClickCellButtonIndex:(VideoCellDelegateClickEventCode)index andCellIndexPath:(NSIndexPath *)cellIndexPath andNavigationController:(UINavigationController *)navigationController andHidesBottomBarWhenPushed:(BOOL)hidesBottomBarWhenPushed andCellModel:(id)model andOtherObject:(id)object andRefreshBlcok:(void (^)(VideoCellRefreshType, BOOL))refreshBlcok
{
    LZVideoListModel *videoModel = (LZVideoListModel*)model;
    
    //**********************************************************
    //*******************  想直接测试动画.解开下面的两句   ***********
    
//    [self openCouponViewWithModel:videoModel nav:navigationController cellIndexPath:cellIndexPath refreshBlock:refreshBlcok];
//    return;
    
    //******************  想直接测试动画.解开上面的两句   ************
    //*********************************************************
    
    @weakify(self);
    if ([self checkLoginStateWithNavigationController:navigationController andHidesBottomBarWhenPushed:YES]) {
        
        self.selectedIndexPathIdentifier = [[NSString stringWithFormat:@"%ld_%ld_coupon",cellIndexPath.section,cellIndexPath.row] copy];
        
        // 如果已登录
        if (videoModel.isCoupons) {
            // 已抢券
            [self showAlertView:LZLocalizedString(@"coupon_geted_remind", nil)];
            self.selectedIndexPathIdentifier = nil;
        }else if ([videoModel.couponsResidueCount isEqualToString:@"0"]){
            // 优惠券抢完
            [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
            self.selectedIndexPathIdentifier = nil;
        }
        else {
            
            // LY ----- 加loading    2017/04/27
            __block BOOL isRequestFinshed = NO;
            LZBaseViewController *vc = navigationController.viewControllers.lastObject;

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (isRequestFinshed == NO) {
                    [vc stopLoadingViewForView:vc.tabBarController.view];
                    [vc startLoadingViewForView:vc.tabBarController.view loadingViewUserInteractionEnabled:YES];
                }
            });
            
            [LZCheckCouponAndGrouponPresenter checkCouponWithPromotionId:videoModel.videoId ResultSuccess:^(id result) {
                @strongify(self);
                isRequestFinshed = YES;
                [vc stopLoadingViewForView:vc.tabBarController.view];
                DLog(@"%@",[NSString stringWithFormat:@"%ld_%ld_coupon",cellIndexPath.section,cellIndexPath.row]);
                if (self.selectedIndexPathIdentifier.length == 0 || ![self.selectedIndexPathIdentifier isEqualToString:[NSString stringWithFormat:@"%ld_%ld_coupon",cellIndexPath.section,cellIndexPath.row]]) {
                    return ;
                }
                
                self.selectedIndexPathIdentifier = nil;
                
                LZPromotionStatusModel *modelTemp = (LZPromotionStatusModel*)result;
                if (modelTemp.isPromotion) {
                    videoModel.isCoupons = YES;
                    // 已抢券
                    [self showAlertView:LZLocalizedString(@"coupon_geted_remind", nil)];
                }
                else if (modelTemp.isExpired) {
                    // 已过期
                    [self showAlertView:LZLocalizedString(@"coupon_expired_remind", nil)];
                }
                else if (modelTemp.isOffLine) {
                    DLog(@"商家已下线");
                    [self showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
                }
                else if (modelTemp.isNull) {
                    // 优惠券抢完
                    videoModel.couponsGetCount = videoModel.couponsTotalCount;
                    if (refreshBlcok) {
                        refreshBlcok(VideoCellRefreshType_Coupon ,YES);
                    }
                    [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
                }
                else {
                    
                    [self openCouponViewWithModel:videoModel nav:navigationController cellIndexPath:cellIndexPath refreshBlock:refreshBlcok];
                }
            } ResultFailed:^(NSString *remind) {
                @strongify(self);
                self.selectedIndexPathIdentifier = nil;
                isRequestFinshed = YES;
                [vc stopLoadingViewForView:vc.tabBarController.view];
            }];
        }
    }

}


- (void)openCouponViewWithModel:(LZVideoListModel *)videoModel nav:(UINavigationController *)navigationController cellIndexPath:(NSIndexPath *)indexP refreshBlock:(void (^)(VideoCellRefreshType, BOOL))refreshBlcok
{
    CGPoint point = [self getViewClickPointCoverInWindowWithIndexPath:indexP nav:navigationController];
    
    UIWindow *w = [UIApplication sharedApplication].keyWindow;
    
    if (!_couponDetailPopView) {
        _couponDetailPopView = [[LZGrabCouponDetailPopView alloc] init];
    }
    self.couponDetailPopView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    [w addSubview:self.couponDetailPopView];
    
    self.couponDetailPopView.animationBeginPoint = point;
    [self.couponDetailPopView showSelfAnimation];
    
    self.statusModelTemp = nil;
    
    
    @weakify(self);
    [LZCouponPresenter getGrabCouponOrFightGroupsDetailWithVideoID:videoModel.videoId ResultSuccess:^(LZGrabCouponAndFightGroupsDetialModel *modelBack) {

        @strongify(self);
        if (modelBack.couponsTotalCount == modelBack.couponsGetCount) {
            // 已结束
            [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
        }else{
            videoModel.couponsGetCount = modelBack.couponsGetCount;
            videoModel.isCoupons = NO;
            if (refreshBlcok) {
                refreshBlcok(VideoCellRefreshType_Coupon ,YES);
            }
            self.couponDetailPopView.detailModel = modelBack;
        }
        
    } ResultFailed:^(NSString *remind) {
       
    }];
    
    
    self.couponDetailPopView.getCouponBlock = ^(){
       
        @strongify(self);
        
        //**********************************************************
        //*******************  想直接测试抢券动画.解开下面的两句   ***********
        
//        [self.couponDetailPopView rotatingAnimationCloseSelf];
//        return ;
        
        //******************  想直接测试抢券动画.解开上面的两句   ************
        //*********************************************************
        
        
        [self.couponDetailPopView setUserInteractionEnabled:NO];
        
        [LZCheckCouponAndGrouponPresenter checkCouponWithPromotionId:videoModel.videoId ResultSuccess:^(id result) {
            @strongify(self);
            [self.couponDetailPopView setUserInteractionEnabled:YES];
            self.statusModelTemp = (LZPromotionStatusModel*)result;
            if (self.statusModelTemp.isPromotion) {
                DLog(@"已抢优惠券");
                [self.couponDetailPopView cancelSelfWithAnimation];
            }
            else if (self.statusModelTemp.isExpired) {
                DLog(@"已过期");
                [self.couponDetailPopView cancelSelfWithAnimation];
            }
            else if (self.statusModelTemp.isOffLine) {
                DLog(@"商家已下线");
                [self.couponDetailPopView cancelSelfWithAnimation];
            }
            else if (self.statusModelTemp.isNull) {
                DLog(@"已结束");
                [self.couponDetailPopView cancelSelfWithAnimation];
            }
            else {
                [self.couponDetailPopView setUserInteractionEnabled:NO];
                [LZCouponPresenter grabCouponWithSellerID:self.couponDetailPopView.detailModel.sellerId PromotionID:self.couponDetailPopView.detailModel.videoId RestaurantName:self.couponDetailPopView.detailModel.restaurantName ResultSuccess:^{
                    
                    @strongify(self);
                    DLog(@"抢券成功");
                    videoModel.couponsGetCount = self.couponDetailPopView.detailModel.couponsGetCount + 1;
                    videoModel.isCoupons = YES;
                    if (refreshBlcok) {
                        refreshBlcok(VideoCellRefreshType_Coupon ,YES);
                    }
                    [self.couponDetailPopView setUserInteractionEnabled:YES];
                    UIViewController *lastVC = navigationController.viewControllers.lastObject;
                    if ([lastVC isKindOfClass:[LZHomePageViewController class]]) {
                        [self.couponDetailPopView rotatingAnimationCloseSelf];
                    }else{
                        [self.couponDetailPopView cancelSelfWithAnimation];
                    [self showAlertView:LZLocalizedString(@"coupon_getcoupon_success_remind", nil)];
                    }
                    
                    
                } ResultFailed:^(NSString *remind) {
                    DLog(@"=-=-==%@",remind);
                    [self.couponDetailPopView setUserInteractionEnabled:YES];
                }];
            }
        } ResultFailed:^(NSString *remind) {
            @strongify(self);
            [self.couponDetailPopView setUserInteractionEnabled:YES];
            
        }];
        
    };
    
    //非旋转结束动画结束后
    self.couponDetailPopView.cancelSelfAcimationEndBlock = ^(){
        @strongify(self);
        if (self.statusModelTemp.isPromotion) {
            DLog(@"已抢优惠券");
            [self showAlertView:LZLocalizedString(@"coupon_geted_remind", nil)];
        }
        else if (self.statusModelTemp.isExpired) {
            DLog(@"已过期");
            [self showAlertView:LZLocalizedString(@"coupon_expired_remind", nil)];
        }
        else if (self.statusModelTemp.isOffLine) {
            DLog(@"商家已下线");
            [self showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
        }
        else if (self.statusModelTemp.isNull) {
            DLog(@"已结束");
            [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
        }
        else {
            
        };

    };

}


/**
 获取点击位置在widow的点

 @param indexP <#indexP description#>
 @param nav <#nav description#>
 @return <#return value description#>
 */
- (CGPoint)getViewClickPointCoverInWindowWithIndexPath:(NSIndexPath *)indexP nav:(UINavigationController *)nav
{
    id tab;
    CGPoint clickPoint = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    UIViewController *lastVC = nav.viewControllers.lastObject;
    
    if ([lastVC isKindOfClass:[LZHomePageViewController class]]) {
        for (UIView *sub in lastVC.view.subviews) {
            if ([sub isKindOfClass:[UITableView class]]) {
                tab = (UITableView *)sub;
            }
        }
    }else{
        for (UIView *sub in lastVC.view.subviews) {
           if ([sub isKindOfClass:[LAMerchantDetailTableView class]]){
                LAMerchantDetailTableView *tabTemp = (LAMerchantDetailTableView *)sub;
                tab = (LAMerchantDetailVideoTableView *)tabTemp.videoTable;
            }
        }
    }
    
    LZVideoTableViewCell *cc = [tab cellForRowAtIndexPath:indexP];
    extern NSInteger couponAndGrouponBgViewTag;
    extern NSInteger couponBgViewTag;
    for (UIView *sub in cc.contentView.subviews) {
        if (sub.tag == couponAndGrouponBgViewTag) {
            for (UIView *couponBgView in sub.subviews) {
                if (couponBgView.tag == couponBgViewTag) {
                    CGRect rectTemp = [couponBgView convertRect:couponBgView.frame toView:nil];
                    clickPoint = CGPointMake(rectTemp.origin.x + rectTemp.size.width/2, rectTemp.origin.y + rectTemp.size.height/2);
                }
            }
        }
    }

    return clickPoint;
}

- (BOOL)checkLoginStateWithNavigationController:(UINavigationController*)navigationController andHidesBottomBarWhenPushed:(BOOL)hidesBottomBarWhenPushed {
    if ([[LZUserModel Instance] isLogin]) {
        return YES;
    }
    else {
        // 如果未登录
        LZLoginViewController * vc = [[LZLoginViewController alloc] init];
        if (hidesBottomBarWhenPushed) {
            vc.hidesBottomBarWhenPushed = YES;
        }
        [navigationController pushViewController:vc animated:YES];
        
        return NO;
    }
}


#pragma mark - LZAlerView

- (void)showAlertView:(NSString*)message {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:message andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
}
@end
